package dao

import (
	"context"
	"mini-app/internal/dal"
	"mini-app/internal/models"
	"strconv"
	"strings"
	"time"
)

type AdCouponDao struct{}

func (AdCouponDao) Create(ctx context.Context, query *dal.Query, name string, salesOff float32, startAt, endAt int64, deviceGroupID string) (err error) {
	o := query.AdCoupon
	d := models.AdCoupon{}
	uuid := strconv.FormatInt(time.Now().Unix(), 10)
	d.ID = uuid
	d.Name = name
	d.SalesOff = salesOff
	d.StartAt = startAt
	d.EndAt = endAt
	d.DeviceGroupID = deviceGroupID
	d.LocationIDs = ""
	d.Status = 0
	err = o.WithContext(ctx).Create(&d)
	return

}

func (AdCouponDao) GetByCondition(ctx context.Context, query *dal.Query, startTime, endTime int64, deviceGroupIds, location_id string) (res []*models.AdCoupon, err error) {
	o := query.AdCoupon
	tx := o.WithContext(ctx)

	tx1 := tx.Where(o.Status.Eq(0)).Or(o.Status.Null())

	var tx2 dal.IAdCouponDo
	if startTime < endTime && startTime > 0 && endTime > 0 {
		tx2 = tx.Where(o.StartAt.Gte(startTime)).
			Where(o.EndAt.Lte(endTime))

	} else if startTime > 0 && endTime == 0 {
		tx2 = tx.Where(o.StartAt.Lte(startTime)).
			Where(o.EndAt.Gte(startTime))

	}

	var tx3 dal.IAdCouponDo
	if deviceGroupIds != "" {
		tx3 = tx.Where(o.DeviceGroupID.Eq(""))

		deviceGroupIdsSep := strings.Split(deviceGroupIds, ",")
		for _, deviceGroupId := range deviceGroupIdsSep {
			tx3 = tx3.Or(o.DeviceGroupID.Eq(deviceGroupId))
		}

	}
	tx = tx.Where(tx1).Where(tx2).Where(tx3)
	if location_id != "" {
		// locationIDsep := strings.Split(location_ids, ",")
		// for _, locationID := range locationIDsep {
		// 	// tx = tx.Where(o.DeviceIDs.In(locationID))
		// 	//to do
		// }
	}
	tx = tx.Order(o.SalesOff.Asc())

	res, err = tx.Find()

	// if device_id != "" {
	// 	for _, coupon := range coupons {
	// 		couponDeviceIDsep := strings.Split(coupon.DeviceIDs, ",")
	// 		for _, couponDeviceID := range couponDeviceIDsep {
	// 			if couponDeviceID == device_id {
	// 				res = append(res, coupon)
	// 			}
	// 		}
	// 	}
	// } else {
	// 	res = coupons
	// }

	return
}

func (AdCouponDao) ModifyByID(ctx context.Context, query *dal.Query, id string, name string, salesOff float32, startAt, endAt int64, deviceGroupID string) (err error) {
	o := query.AdCoupon
	tx := o.WithContext(ctx).Where(o.ID.Eq(id))
	_, err = tx.First()
	if err != nil {
		return err
	}

	tx.UpdateColumn(o.Name, name)
	tx.UpdateColumn(o.SalesOff, salesOff)
	tx.UpdateColumn(o.StartAt, startAt)
	tx.UpdateColumn(o.EndAt, endAt)
	tx.UpdateColumn(o.DeviceGroupID, deviceGroupID)
	return
}

func (AdCouponDao) DeleteByID(ctx context.Context, query *dal.Query, id string) (err error) {
	o := query.AdCoupon
	tx := o.WithContext(ctx).Where(o.ID.Eq(id))
	_, err = tx.First()
	if err != nil {
		return err
	}

	tx.UpdateColumn(o.Status, 1)
	return
}
